<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="FreeRTOS的消息队列模块，不仅提供了通用的消息队列功能，而且还提供了消息队列集合功能。对于需要从多个消息队列中获取数据的场景，FreeRTOS提供的消息队列集合功能，简化了等待多个消息队列有数据的代码编写方式。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-使用消息队列集合">
<meta property="og:url" content="http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="FreeRTOS的消息队列模块，不仅提供了通用的消息队列功能，而且还提供了消息队列集合功能。对于需要从多个消息队列中获取数据的场景，FreeRTOS提供的消息队列集合功能，简化了等待多个消息队列有数据的代码编写方式。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/queue-set.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/internal_info.png">
<meta property="article:published_time" content="2022-12-13T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-02T14:01:36.079Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/queue-set.png">


<link rel="canonical" href="http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/","path":"2022/12/14/FreeRTOS-use-queueset/","title":"FreeRTOS-使用消息队列集合"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-使用消息队列集合 | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-使用消息队列集合 | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-使用消息队列集合
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-12-14 00:00:00" itemprop="dateCreated datePublished" datetime="2022-12-14T00:00:00+08:00">2022-12-14</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>7 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>

<p>FreeRTOS的消息队列模块，不仅提供了通用的消息队列功能，而且还提供了<code>消息队列集合</code>功能。对于需要从多个消息队列中获取数据的场景，FreeRTOS提供的消息队列集合功能，简化了等待多个消息队列有数据的代码编写方式。</p>
</center>

<span id="more"></span>

<hr>
<p>关于FreeRTOS消息队列内部的一些实现细节，可以参考<a href="https://fengxun2017.github.io/2022/12/08/FreeRTOS-queue-internal-details/">FreeRTOS-消息队列内部细节</a><br>普通消息队列的使用，可以参考<a href="https://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/">FreeRTOS-使用消息队列</a></p>
<p>考虑在某个场景下，我们必须要创建多个消息队列，并且从这多个消息队列中获取数据。使用普通消息队列提供的API 时，我们得不停地在多个消息队列之间进行轮训，以查看哪个消息队列有数据了，但轮训方式必然效率低下。<br>而<code>消息队列集合</code>则可以高效的处理这种问题，我们只需要将 <code>所有需要等待数据的消息队列</code>，都添加到一个消息队列集合中，之后等待这个消息队列集合即可。没有数据时，等待消息的任务不占用CPU时间，一但<code>消息队列集合</code>中的任何一个<code>消息队列</code>接收到消息了，任务就会结束等待，并可以从消息队列集合中提取到 接收到消息的<code>消息队列的句柄</code>，之后只要使用该句柄从对应的消息队列中提取实际消息即可。</p>
<p>FreeRTOS的<code>消息队列集合</code>，其本质也是一个消息队列。不同的是，一般的消息队列中存放的是消息，而<code>消息队列集合</code>中存放的是 <code>消息队列句柄</code>，用来通知某个消息队列有数据了。<br>如下图所示，假设消息队列 <code>queue1</code>和<code>queueu2</code>都被“关联到”到消息队列集合<code>queue_set</code>中了。之后，消息队列<code>queue1</code>和<code>queueu2</code>均接收到一条消息，此时，消息队列集合<code>queue_set</code>中就会被推送两个消息（两个消息分别为<code>queue1</code>和<code>queueu2</code>的句柄），表示该消息队列集合中存在消息队列接收到消息了。我们从消息队列集合<code>queue_set</code>中提取出接收到消息的 消息队列句柄，根据该句柄就可以到对应消息队列中获取消息了。<br><img src="/2022/12/14/FreeRTOS-use-queueset/queue-set.png"></p>
<p>因此，<code>消息队列集合</code>的使用可以总结为三步:</p>
<ul>
<li>创建一个消息队列集合</li>
<li>将需要等待消息的 消息队列 均关联到创建的消息队列集合上</li>
<li>等待消息队列集合有消息。一有消息，则可以从中提取到实际接收到消息的 消息队列 的句柄。利用该句柄，再到实际消息队列中提取消息。</li>
</ul>
<br>

<p>使用<code>消息队列集合</code>，需要在工程配置文件<code>FreeRTOSConfig.h</code>中添加如下配置：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configUSE_QUEUE_SETS		1</span></span><br></pre></td></tr></table></figure>

<p>创建消息队列集合的API为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">QueueSetHandle_t <span class="title function_">xQueueCreateSet</span><span class="params">( <span class="type">const</span> UBaseType_t uxEventQueueLength )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>uxEventQueueLength：该值应该为添加到消息队列集合中的 消息队列的大小的总和。如前文图片中<code>queue1</code>和<code>queue2</code>的大小均为3，则<code>queue_set</code>需要设置为6。因为queue_set中保存的消息是接收到消息的那个消息队列的句柄，每收到一个消息，消息队列集合中都会被推送对应收到消息的消息队列句柄，所以为了保存所有接收事件，需要将消息队列集合的大小设置为其所包含的所有消息队列的大小之和（注意，消息队列的大小，指的是包含“消息”的数量，并不是实际所占内存大小，消息队列集合由于存的“消息”是消息队列句柄，即一个指针，因此实际消息存储所占大小应该是uxEventQueueLength*4 ）。</p>
</li>
<li><p>返回值：<code>消息队列集合</code>句柄，用来唯一识别创建的这个消息队列集合。如果堆内存资源不够，则返回NULL。</p>
</li>
</ul>
<p><code>消息队列集合</code>创建成功后，需要将那些需要同时等待的消息队列“添加到”这个消息队列集合中，API为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xQueueAddToSet</span><span class="params">( QueueSetMemberHandle_t xQueueOrSemaphore,</span></span><br><span class="line"><span class="params">                            QueueSetHandle_t xQueueSet )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xQueueOrSemaphore：要添加到消息队列集合中的消息队列句柄。（从名字可看到，信号量也可以添加到消息队列集合中，因为FreeRTOS的信号量就是使用消息队列来实现的，本文不涉及信号量。）</li>
<li>xQueueSet：消息队列集合句柄，即<code>xQueueCreateSet</code>函数的返回值。</li>
</ul>
<p>添加完成之后，使用监听API，消息队列集合中的任何一个消息队列收到消息时，我们都能收到事件通知：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">QueueSetMemberHandle_t <span class="title function_">xQueueSelectFromSet</span><span class="params">( QueueSetHandle_t xQueueSet,</span></span><br><span class="line"><span class="params">                                            <span class="type">const</span> TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xQueueSet：消息队列集合句柄。</li>
<li>xTicksToWait：监听等待的时间，应该使用<code>pdMS_TO_TICKS(ms)</code>将时间转换成内核可以识别的tick数。</li>
<li>返回值：即收到消息的消息队列句柄。为NULL表示超时了，没有收到消息。</li>
</ul>
<p><a href="https://fengxun2017.github.io/2022/12/08/FreeRTOS-queue-internal-details/">FreeRTOS-消息队列内部细节</a>一文中，我们介绍了消息队列的内部实现细节。上文提到，消息队列集合，实际也是一个消息队列，只是这个队列中存放的是那些接收到消息的<code>消息队列句柄</code>。即<code>消息队列集合</code>中的任意一个<code>消息队列</code>收到消息时，内核都会推送收到消息的这个<code>消息队列句柄</code>到消息队列集合中，如下图所示：</p>
<p><img src="/2022/12/14/FreeRTOS-use-queueset/internal_info.png"><br>当调用<code>xQueueAddToSet( queue1, queue_set )</code>将消息队列<code>queue1</code>加入到消息队列集合<code>queue_set</code>中，实际是让消息队列<code>queue1</code>控制信息中的<code>pxQueueSetContainer</code>成员指向了消息队列集合<code>queue_set</code>。<br>之后，其它任务调用<code>xQueueSend(queue1, &amp;data)</code>向消息队列<code>queue1</code>中发送数据时，函数内部实际是做了两件事：一是向消息队列<code>queue1</code>中推送数据，此外，还将消息队列<code>queue1</code>的句柄发送到了消息队列集合<code>queue_set</code>中（消息队列集合本身也是消息队列）。因此，调用<code>xQueueSelectFromSet</code>监听消息队列集合的任务，就可以在任意消息队列收到消息后收到通知，并根据通知（那个收到消息的消息队列句柄），去对应消息队列中获取消息。</p>
<p>我们以一个示例程序，演示<code>消息队列集合</code>API 的使用。<br>我们创建两个发送任务<code>sender1</code>和<code>sender2</code>，以及两个消息队列<code>queue1</code>和<code>queue2</code>。<code>sender1</code>向消息队列<code>queue1</code>中发送消息，<code>sender2</code>向消息队列<code>queue2</code>中发送消息。<br>消息队列<code>queue1</code>和<code>queue2</code>，均添加在消息队列集合<code>queue_set</code>中。<br>再创建一个接收任务<code>receiver</code>，该任务监听<code>queue_set</code>，一有事件，则提取出消息队列句柄，再从对应的消息队列中获取数据。</p>
<p>main函数代码：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> &#123;</span></span><br><span class="line">    <span class="type">int</span> cmd_id;</span><br><span class="line">    <span class="type">int</span> other;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">QueueHandle_t queue1;</span><br><span class="line">QueueHandle_t queue2;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    bsp_init();</span><br><span class="line">    BACKLIGHT_ON();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建两个消息队列</span></span><br><span class="line">    queue1  = xQueueCreate(<span class="number">5</span>, <span class="keyword">sizeof</span>(<span class="keyword">struct</span> MyData));</span><br><span class="line">    queue2  = xQueueCreate(<span class="number">5</span>, <span class="keyword">sizeof</span>(<span class="keyword">struct</span> MyData));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建消息队列集合，大小应该是其中所包含消息队列的大小总和</span></span><br><span class="line">    QueueSetHandle_t queue_set = xQueueCreateSet(<span class="number">5</span>+<span class="number">5</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != queue1 &amp;&amp; <span class="literal">NULL</span> != queue2 &amp;&amp; <span class="literal">NULL</span> != queue_set) &#123;</span><br><span class="line">        <span class="comment">// 将两个消息队列，“添加到”消息队列集合中</span></span><br><span class="line">        xQueueAddToSet( queue1, queue_set );</span><br><span class="line">        xQueueAddToSet( queue2, queue_set );</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建发送和接收任务</span></span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(sender1_task, <span class="string">&quot;sender1_task&quot;</span>, <span class="number">100</span>, queue1, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">         &amp;&amp; pdPASS == xTaskCreate(sender2_task, <span class="string">&quot;sender2_task&quot;</span>, <span class="number">100</span>, queue2, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">         &amp;&amp; pdPASS == xTaskCreate(receiver_task, <span class="string">&quot;receiver_task&quot;</span>, <span class="number">100</span>, queue_set, <span class="number">1</span>, <span class="literal">NULL</span>)) &#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;something wrong\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>发送任务的代码：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">sender1_task</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    QueueHandle_t queue1 = (QueueHandle_t)pvParameters;</span><br><span class="line">    </span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> <span class="title">data</span>;</span></span><br><span class="line">    data.cmd_id = <span class="number">0</span>;</span><br><span class="line">    data.other = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        xQueueSend(queue1, &amp;data, <span class="number">0</span>);</span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">sender2_task</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    QueueHandle_t queue2 = (QueueHandle_t)pvParameters;</span><br><span class="line">    </span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> <span class="title">data</span>;</span></span><br><span class="line">    data.cmd_id = <span class="number">1</span>;</span><br><span class="line">    data.other = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        xQueueSend(queue2, &amp;data, <span class="number">0</span>);</span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接收任务的代码：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">receiver_task</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    QueueSetHandle_t queue_set = (QueueSetHandle_t)pvParameters;</span><br><span class="line">   </span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> <span class="title">data</span>;</span></span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="comment">// 等待消息队列集合中的某个消息队列接收到消息</span></span><br><span class="line">        QueueSetMemberHandle_t handle = xQueueSelectFromSet(queue_set, pdMS_TO_TICKS(<span class="number">1500</span>));</span><br><span class="line">        <span class="keyword">if</span>( handle == queue1 )&#123;</span><br><span class="line">            <span class="comment">// 是消息队列1 收到消息了</span></span><br><span class="line">            xQueueReceive( queue1, &amp;data, <span class="number">0</span> );</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;receive from queue1 cmd:%d\n&quot;</span>, data.cmd_id);</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span>( handle == queue2 ) &#123;</span><br><span class="line">            <span class="comment">// 是消息队列2 收到消息了</span></span><br><span class="line">            xQueueReceive(queue2, &amp;data, <span class="number">0</span> );</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;receive from queue2 cmd:%d\n&quot;</span>, data.cmd_id);</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (handle == <span class="literal">NULL</span>) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;timeout\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果如下所示：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">receive from queue1 cmd:0</span><br><span class="line">receive from queue2 cmd:1</span><br><span class="line">receive from queue1 cmd:0</span><br><span class="line">receive from queue2 cmd:1</span><br><span class="line">receive from queue1 cmd:0</span><br><span class="line">receive from queue2 cmd:1</span><br><span class="line">receive from queue1 cmd:0</span><br><span class="line">receive from queue2 cmd:1</span><br><span class="line">receive from queue1 cmd:0</span><br><span class="line">receive from queue2 cmd:1</span><br><span class="line">....</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<br>

<p>注意，上文代码仅仅是为了演示<code>消息队列集合</code>的使用方法。实际开发中，我们应该尽量避免使用多个消息队列（浪费资源）。一般情况下，使用一个更大的消息队列，并通过如下自定义数据类型中的<code>type</code>字段来区分数据的不同发送方（或区分数据的不同处理方式），发送变长数据也可以通过传递数据指针来实现：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> &#123;</span></span><br><span class="line">    <span class="type">int</span> type;</span><br><span class="line">    <span class="type">char</span> data[N]</span><br><span class="line">    <span class="type">int</span> other_data_len;</span><br><span class="line">    <span class="type">char</span> *other_data;</span><br><span class="line"></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>
<br>
FreeRTOS交流QQ群-663806972


    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/" title="FreeRTOS-使用消息队列集合">http://fengxun2017.github.io/2022/12/14/FreeRTOS-use-queueset/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/12/12/FreeRTOS-use-queue/" rel="prev" title="FreeRTOS-使用消息队列">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-使用消息队列
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/12/15/FreeRTOS-use-binary-semaphore/" rel="next" title="FreeRTOS-使用二值信号量">
                  FreeRTOS-使用二值信号量 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
